package cs2340.flyingkiwi.todoapp;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

/**
 * This class simulates making a new item.
 * 
 * @author Group Flying Kiwi
 * @version 15 Mar 2012
 * 
 * It has four text fields for title, description, location, and due date
 * It is almost identical to EditCategory class except some more text fields.
 */

public class EditItem extends Activity{
	
	private EditText mTitleText;
	private EditText mDescriptionText;
	private EditText mLocationText;
	private DatePicker mDuedatePicker;
	
	private String accountId;
	private String categoryId;
    private Long mRowId;
    private ToDoAppDbAdapter mDbHelper;
    
    /**
	 * onCreate method
	 * Displays the edit_item view and gets or creates an Item id. Saves
	 * the data in the text fields if Create Item button is clicked.
	 * Does not save data if Cancel is clicked.
	 * @param savedInstanceState
	 */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	Log.d("EditItem onCreate", "Beginning");
        super.onCreate(savedInstanceState);
        mDbHelper = new ToDoAppDbAdapter(this);
        mDbHelper.open();
        
        setContentView(R.layout.edit_item);
        setTitle(R.string.item_edit);

        mTitleText = (EditText) findViewById(R.id.item_title);
        mDescriptionText = (EditText) findViewById(R.id.description);
        mLocationText = (EditText) findViewById(R.id.location);
        mDuedatePicker = (DatePicker) findViewById(R.id.datePicker1);
        
        Button confirmButton = (Button) findViewById(R.id.item_edit_button);
        Button cancelButton = (Button) findViewById(R.id.cancel);
        
        Log.d("EditItem onCreate", "got done with widgets");
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            
            if (extras != null) {
            Log.d("EditItem onCreate", "create extras.size = " + extras.size());
            if(extras.size() == 0) {
            	accountId = null;
                categoryId = null;
                mRowId = null;
            } 
            else {
            	accountId = extras.getString(ToDoAppDbAdapter.KEY_ITEM_ACCOUNTID);
                categoryId = extras.getString("categoryId");
                Log.d("EditItem onCreate", "edit extras.size = " + extras.size());
                if(extras.size() == 3)
                	mRowId = extras.getLong(ToDoAppDbAdapter.KEY_ITEM_ROWID);
                else
                	mRowId = null;
            }
            }
        } 
        else {
        	accountId = (String) savedInstanceState.getSerializable(ToDoAppDbAdapter.KEY_ITEM_ACCOUNTID);
            categoryId = (String) savedInstanceState.getSerializable(ToDoAppDbAdapter.KEY_CATEGORY_ROWID);
            mRowId = (Long) savedInstanceState.getSerializable(ToDoAppDbAdapter.KEY_ITEM_ROWID);
        }
        
        populateFields();
        
        confirmButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	Log.d("Edititem onClick", "before save state");
                saveState();
            	setResult(RESULT_OK);
                finish();
            }

        });
        
        cancelButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	Toast.makeText(EditItem.this, "Canceled", Toast.LENGTH_LONG).show();
            	setResult(RESULT_CANCELED);
               	finish();
            }

        });
    }
    
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    
    /**
     * This method fetches the database and gets previous title when editing item.
     */
    private void populateFields(){
    	Log.d("EditItem populate", "mRowId " + mRowId);
    	if(mRowId != null){
    		Cursor item = mDbHelper.fetchItem(mRowId);
    		startManagingCursor(item);
    		mTitleText.setText(item.getString(
    				item.getColumnIndexOrThrow(ToDoAppDbAdapter.KEY_ITEM_TITLE)));
    		mDescriptionText.setText(item.getString(
    				item.getColumnIndexOrThrow(ToDoAppDbAdapter.KEY_ITEM_DESCRIPTION)));
    		mLocationText.setText(item.getString(
    				item.getColumnIndexOrThrow(ToDoAppDbAdapter.KEY_ITEM_LOCATION)));
    		
    		String dateString = item.getString(
    				item.getColumnIndexOrThrow(ToDoAppDbAdapter.KEY_ITEM_DUEDATE));
    		String[] dateInfo = dateString.split(" ");

    		Log.d("EditItem populate", "dateInfo " + dateInfo[1] + " dateInfo2 " + dateInfo[2] + " dateInfo0 " + dateInfo[0]);
    		mDuedatePicker.updateDate(Integer.parseInt(dateInfo[2]), 
    				Integer.parseInt(dateInfo[0]), Integer.parseInt(dateInfo[1]));
    	}
    }
    
    
    /**
     * This method saves the user input.
     */
    private void saveState(){
    	String title = mTitleText.getText().toString();
    	String description = mDescriptionText.getText().toString();
    	String location = mLocationText.getText().toString();
    	String duedate = String.valueOf(mDuedatePicker.getMonth()) + " " 
    						+ String.valueOf(mDuedatePicker.getDayOfMonth()) + " "
    						+ String.valueOf(mDuedatePicker.getYear());
    	Log.d("EditItem, SaveState", "mRowId = " + mRowId);
    	if(mRowId == null){
    		long id = mDbHelper.createItem(title, description, location, duedate, accountId, categoryId);
    		Toast.makeText(EditItem.this, title + " created!", Toast.LENGTH_LONG).show();
    		Log.d("EditItem, SaveState", "after createItem id = " + id);
    		if(id>0){
    			mRowId = id;
    		}
    	}
    	else{
    		Toast.makeText(EditItem.this, title + " updated!", Toast.LENGTH_LONG).show();
    		mDbHelper.updateItem(mRowId, title, description, location, duedate);
    	}
    }
    
    public long getRowId(){
    	return mRowId;
    }
}
